<?php

$report_locale=new cLocale("report_php.inc",$_SESSION["guser_preferences"]["language"]);
/*****************************************************************************************
Function Name                 :navigatePage
No. of Arguments        :4
Arguments                :$page_no - current page no (If page_no is null then it is set to 1)
                         $arrays - associative array of records
                         $row_count - no of records to be displayed set by the user in the
                                 preferences
                         $query_string_array - optional associative array of query strings to
                                 be passed at the time of page navigation.
Action                        :Splits the given array ($arrays) into pages having $row_count
                                records per page and returns it. Displays the links for page
                                navigation, location of the current records and the
                                total number of records.
Returns                        :returns splitted array
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :R.Lakshmi Narayanan
Modified On                :28 May 2003
*****************************************************************************************/
function navigatePage($page_no,$arrays,$row_count,$query_string_array="")
        {
        global $report_locale;
        if ($page_no=="" || $page_no<1)
                $page_no=1;

        // finding the last page
        $last_page=ceil(count($arrays) / $row_count);
    if($page_no>$last_page)
            $page_no=$last_page;
        // finding the row from which the records are displayed.
        $offset=($page_no-1)*$row_count;

        // fetching the records from the offset
        $arrays1=array_slice($arrays,$offset,$row_count);
        $from=$offset+1;
        $to=count($arrays1)+$offset;
        if($_GET["action"]=="print_report")
                {
                echo "<div align=\"center\">".$page_no."/".$last_page."</div>";
                if($last_page > 1 && $page_no != $last_page)
                        echo "<div align=\"right\">".returnLink($PHP_SELF,"Contd...",array_merge($query_string_array,array("page_no"=>$page_no+1,"action"=>$_GET["action"])))."</div>";
                }
        else
                {
                echo "<div align=\"left\">".sprintf("Showing (%1\$d - %2\$d) of %3\$d",$from,$to,count($arrays))."Page"." ";
                for($i=1;$i<=$last_page;$i++)
                        {
                        if($page_no==$i)
                                echo "<font size=\"3\">$i </font>";
                        else
				{
				//$query_string_array=array();
                                echo returnLink($PHP_SELF,$i,array_merge($query_string_array,array("page_no"=>$i)))." ";
				}
                        }
                echo "</div>";
                }
        return $arrays1;
        }

/*****************************************************************************************
Function Name                 :showPrintableReportLink
No. of Arguments        :1
Arguments                :$query_string - Optional variable containing the query strings to be
                                passed to the report.
Action                        :Displays "Printable Report" link in the page.
Returns                        :Nil
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :R.Lakshmi Narayanan
Modified On                :29 May 2003
*****************************************************************************************/

function showPrintableReportLink($query_string="")
        {
        global $report_locale;
        if($query_string)
                $query_string=array_merge(array("action"=>"print_report"),$query_string);
        else
                $query_string=array("action"=>"print_report");
        echo "<br /><div align=\"right\">";
        //echo returnLink($_SERVER["PHP_SELF"],"^ Top ^",$_SERVER["PHP_SELF"], "_self","0")." | ";
	echo returnLink($_SERVER["PHP_SELF"],"Printable Report",$query_string, "_blank","1")."  ";
        //$query_string=array_merge($query_string,array("ob"=>"1"));
        //echo returnLink($_SERVER["PHP_SELF"],"View as PDF",$query_string, "_blank","2")." | ";
        //$query_string=array_merge($query_string,array("full_page"=>"1"));
        unset($query_string["ob"]);
	//echo returnLink($_SERVER["PHP_SELF"],"Full Page View",$query_string, "_blank","2");
        echo "</div>";
        }


function showExcelReportLink($query_string="")
        {
        global $report_locale;
        if($query_string)
                $query_string=array_merge(array("action"=>"excel_report"),$query_string);
        else
                $query_string=array("action"=>"excel_report");
        echo "<br /><div align=\"right\">";
        
	echo returnLink($_SERVER["PHP_SELF"],"Export Excel",$query_string,"" ,"1","Click here to export the report to Excel format")."  ";

        unset($query_string["ob"]);
	
        echo "</div>";
        }


/*****************************************************************************************
Function Name                 :doHorizontalTable
No. of Arguments        :3
Arguments                :$table_details -  Associative array of records to be displayed in
                                table format.
                         $width - Optional variable to set the width for the table.
                         $title - Optional variable to set the title for the table.
Action                        :Displays the values of the $table_details array in table format.
                         This function is used to display more than one record.
Returns                        :Nil
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :R.Lakshmi Narayanan
Modified On                :28 May 2003
*****************************************************************************************/


function
doHorizontalTable($table_details,$width="100%",$title="",$column_properties="",
$set_column_heading=true,$highlight=true,
$serial_no=false,$report_table="",$class="link_head")
        {
        if ($table_details)
                {
                $html_table_string =
createHorizontalTable($table_details,$width,$title,$column_properties,
$set_column_heading,$highlight,$serial_no,$report_table,$class);
                echo $html_table_string;
                }
        }


function
createHorizontalTable($table_details,$width="100%",$title="",$column_properties=
"",$set_column_heading=true,$highlight=true,
$serial_no=false,$report_table="",$class="link_head")
        {
        if ($table_details)
                {
                $column_properties=($column_properties)?$column_properties:array();
		if ($report_table !="")
			$table_string="<div class=\"$report_table\" id=\"data\">";
		else
			$table_string="";
		$table_string.= "<table align=\"center\" width=\"$width\"><caption>$title</caption>";
		if($set_column_heading)
                        {
			$table_string.="<thead class=\"$class\"><tr>";
			if ($serial_no==true)
				$table_string.="<th> No </th>";
			$colcount=0; //for setting the footer colspan
			foreach($table_details[0] as $key=>$value)
                                {
                                $table_string.= "<th>$key</th>";
				$colcount++;
				}
			$table_string.="</tr></thead><tfoot><tr><td colspan=\"$colcount\"> </td></tr></tfoot>";
			}
                $i=0;
                $cnt=count($table_details);
		$table_string.="<tbody>";
                for($j=0; $j<$cnt; $j++)
                        {
                        if($highlight)
                                $class=($i=!$i)?"row1":"row2";
                        $table_string.="<tr class=\"$class\">";
			if ($serial_no==true)
				{
				$m=$j+1;
				if ($m < $cnt)
					$table_string.="<td>".$m."</td>";
				}
			foreach($table_details[$j] as $key=>$value)
                                {
                                $table_string.= "<td style=\"".$column_properties[$key]."\">".$value."</td>";
                                }
                        $table_string.= "</tr>";
                        }
                $table_string.= "</tbody></table>";
		if ($report_table !="")
			 $table_string.= "</div>";
		return $table_string;
                }
        }
/*****************************************************************************************
Function Name                 :doVerticalTable
No. of Arguments        :3
Arguments                :$table_details -  Associative array of records to be displayed in
                                table format.
                         $width - Optional variable to set the width for the table.
                         $title - Optional variable to set the title for the table.
Action                        :Displays the values of the $table_details array in table format.
                         This function is used to display only one record.
Returns                        :Nil
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :R.Lakshmi Narayanan
Modified On                :28 May 2003
*****************************************************************************************/

function doVerticalTable($table_details,$width="100%",$title="",$set_column_heading=true,$highlight=true)
        {
        if ($table_details)
                {
                $html_table_string = createVerticalTable($table_details,$width,$title,$set_column_heading,$highlight);
                echo $html_table_string;
                }
        }

function createVerticalTable($table_details,$width="100%",$title="",$set_column_heading=true,$highlight=true)
        {
        if ($table_details)
                {
                $table_string= "<table align=\"center\" width=\"$width\" cellpadding=\"5\">";
                if ($title!="")
			$table_string.= "<tr><td colspan=\"2\" class=\"link_head\"><caption>$title<caption></td></tr>";
                $i=0;
                foreach($table_details as $var)
                        {
                        foreach($var as $key=>$value)
                                {
                                if($highlight)
                                        $class=($i=!$i)?"row1":"row2";
                                $table_string.="<tr class=\"$class\">";
                                if($set_column_heading)
                                        {
                                        $table_string.="<td width=\"50%\" height=\"20px\" valign=\"top\"><b>$key</b></td>";
                                        }
                                $table_string.="<td width=\"50%\" valign=\"middle\">$value</td>";
                                $table_string.="</tr>";
                                }
                        }
                $table_string.="</table>";
                return $table_string;
                }
        }
        

/*****************************************************************************************
Function Name                 :sortArray
No. of Arguments        :3
Arguments                :$arrays - Associative array of records
                         $column_name - Name of the column against which the $arrays is
                         sorted or grouped.
                         $sort_by - Optional variable when set, sorts the $arrays in
                         ascending or descending order against $column_name.
                         $group - Optional variable when set, groups the $arrays against
                         $column_name.
Action                        :It sorts or groups the $arrays against the $column_name and returns it.
                                The $arrays can be sorted in ascending or descending order by
                                setting the variable $sort_by to "ascending" or "descending"
                                respectively. The $arrays are grouped when $group is set to "yes".
Returns                        :array of values.
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :S.Gnanavel
Modified On                :28 May 2003
*****************************************************************************************/

function sortArray($arrays,$column_name,$sort_by="",$group="")
        {
        for($i=0;$i<count($arrays);$i++)
                $column_wise[$i]=$arrays[$i][$column_name];
        if($sort_by == "ascending")
                {
                //asort($column_wise);
                natcasesort($column_wise);
                }
        elseif($sort_by == "descending")
                arsort($column_wise);
        foreach($column_wise as $index=>$value)
                {
                if ($group == "yes")
                        {
                        //unset($arrays[$index][$column_name]);
                        $grouped_arrays[$value][]=$arrays[$index];
                        }
                else
                        $grouped_arrays[]=$arrays[$index];
                }
        return $grouped_arrays;

        }

/*****************************************************************************************
Function Name           :sumColumnValues
No. of Arguments        :2
Arguments               :$arrays - Associative array of records
                         $column_array - Array of columns for which sum of all values to be
                         calculated.
Action                  :Calculates the sum of all values for the columns in $column_array
                                and returns an array containing the sum of all the values.
Returns                 :array of sum of values of all the columns in $column_array.
Created By              :S.Gnanavel
Created On              :14 March 2003
Modified By             :S.Gnanavel
Modified On             :28 May 2003
*****************************************************************************************/

function sumColumnValues($arrays,$column_array,$decimal="2",$total= "")
        {
	if($arrays)
	foreach ($arrays as $column_value)
		{
		foreach($column_array as $column_name)
			{
			if ($column_value[$column_name] > 0)
				$sum[$column_name]+=$column_value[$column_name];
			}
		}
	if($total)
		{
		$sum[$total]="<font size=4 color=blue>Total</font>";
		}
        return $sum;
        }

/*****************************************************************************************
Function Name                 :numberFormatColumn
No. of Arguments        :2
Arguments                :$arrays - Associative array of records
                         $column_array - Array of columns for which all values are to be
                                 formatted to two decimal places.
Action                        :Formats all values for the columns in $column_array to two decimal places
                                and returns the formatted array.
Returns                        :returns an number formatted array with two decimal places.
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :S.Gnanavel
Modified On                :28 May 2003
*****************************************************************************************/
function numberFormatColumn($arrays,$column_array)
        {
        foreach($column_array as $column)
                {
                for($i=0;$i<count($arrays);$i++)
                        $arrays[$i][$column]=number_format($arrays[$i][$column],2);
                }
        return $arrays;
        }

/*****************************************************************************************
Function Name                 :dateFormatColumn
No. of Arguments        :2
Arguments                :$arrays - Associative array of records
                         $column_array - Array of columns whose date values are to be formatted.
Action                        :Formats the date values for the columns in $column_array to user
                                readable format dd-mon-yyyy and returns the format array.
Returns                        :returns the date formatted array.
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :S.Gnanavel
Modified On                :28 May 2003
*****************************************************************************************/

function dateFormatColumn($arrays,$column_array)
        {
        foreach($column_array as $column)
                {
                for($i=0;$i<count($arrays);$i++)
                        $arrays[$i][$column]=showDate($arrays[$i][$column]);
                }
        return $arrays;
        }

/*****************************************************************************************
Function Name                 :showDate
No. of Arguments        :1
Arguments                :$given_date - Date to be formatted
Action                        :Formats the date in database format to user readable form dd-mon-yyyy and
                                returns it.
Returns                        :Formatted date.
Created By                :S.Gnanavel
Created On                :14 March 2003
Modified By                :S.Gnanavel
Modified On                :28 May 2003
*****************************************************************************************/

function showDate($given_date,$format="d-M-Y")
        {
        // convert the date string  to array.
        $date_array=explode('-', $given_date);
        //  Calculate time stamp.
        $stamp=mktime(0,0,0,$date_array[1], $date_array[2], $date_array[0]);
        //  retrieves the date from the timestamp.
        return (date ($format, $stamp));
        }

function fillNA(&$menu_item, $key, $string)
        {
        if ($menu_item == NULL || strcmp($menu_item,"")==0)
                $menu_item = "$string";
        else
                $menu_item = "$menu_item";
        }

function setNA(&$menu,$string="--")
        {
        for ($i=0;$i<count($menu);$i++)
                array_walk ($menu[$i],'fillNA', $string);
        }

/*
Function        : getReportDetails

Arguments        : $member_id, $report_id

Action                : Fetches the column_names and display names for the given $report_id preferred by the member

Author                : S.Gnanavel

Created on        : 11/11/2003
*/
function getReportDetails($member_id,$customization_id)
        {
        //include(DOCINCLUDES."global_files/tables.inc");
	//include_once(DOCINCLUDES."global_files/global_pgsql.inc");
	global $db,$sql;
	//$sql= new pgSql();
	//$db= new cDatabase();
        // get the columns for the report from member's table
      $db->query="select mcm.fetch_column, mp.privilege_desc, mcm.permission, mcm.db_column_name, mcm.script_variable_name, rc.display_name, rc.display_order, rc.style, rc.display_summary, rc.decimal_places, rc.format_details, rc.format_date from $master_column_mapping_table mcm, $report_customization_table rc, $master_privilege_table mp, $master_report_table mr
                                where rc.customization_id='$customization_id' and mcm.column_id=rc.column_id and rc.display_order is not NULL and mcm.privilege_id=mp.privilege_id and mr.report_id=mcm.report_id order by rc.display_order;";
      
	
        $db->runQuery();
	
        $report_details=$db->returnArrays();

        // if the member has not set the preferences then fetch the details from master table
//         if(!$report_details)
//                 {
//                 $db->query="select mcm.fetch_column, mp.privilege_desc, mcm.permission, mcm.db_column_name, mcm.script_variable_name, mrc.display_name, mrc.display_order, mrc.style, mrc.display_summary, mrc.decimal_places, mrc.format_details, mrc.format_date  from $master_column_mapping_table mcm, $master_report_customization_table mrc, $master_privilege_table mp, $master_report_table mr
//                                 where mr.report_code='$report_code' and mcm.column_id=mrc.column_id and mrc.display_order is not NULL  and mcm.privilege_id=mp.privilege_id and mr.report_id=mcm.report_id order by mrc.display_order;";
//                 $db->runQuery();
//                 $report_details=$db->returnArrays();
//                 }
	  if($report_details)
                {
                for($i=0;$i<count($report_details);$i++)
                        {
                        //if(strchr($_SESSION["gprivilege"][$member_id][$report_details[$i]["privilege_desc"]],$report_details[$i]["permission"]))
                                //{
                                $script_variable_name=$report_details[$i]["script_variable_name"];
                                if($report_details[$i]["fetch_column"]=='t')
                                        {
                                        $db_column_name=$report_details[$i]["db_column_name"];
                                        $column_mapping[$db_column_name]=$script_variable_name;
                                        }
                                if($report_details[$i]["display_summary"])
                                        {
                                        $summary_columns[]=$script_variable_name;
                                        }
                                // get the preferred name against script variable name only when display_order is specified
                                if($report_details[$i]["display_order"] > 0)
                                        {
                                        $display_name=$report_details[$i]["display_name"];
                                        $display_columns[$script_variable_name]=$display_name;
                                        if($report_details[$i]["style"])
                                                $column_style[$display_name]=$report_details[$i]["style"];
                                        if($report_details[$i]["display_summary"] == 't')
                                                $display_summary_columns[]=$script_variable_name;
                                        if($report_details[$i]["decimal_places"] != "")
                                                $decimal_places[$script_variable_name]=$report_details[$i]["decimal_places"];
                                        if($report_details[$i]["format_details"])
                                                $format_details[$script_variable_name]=$report_details[$i]["format_details"];
                                        if($report_details[$i]["format_date"])
                                                $format_date[$script_variable_name]=$report_details[$i]["format_date"];
                                        }
                                //}
                        }
               	// return the details of the columns to be fetched from database and display names for the report
                $report_customization_details["column_mapping"]=$column_mapping;
                $report_customization_details["display_columns"]=$display_columns;
                $report_customization_details["column_style"]=$column_style;
                $report_customization_details["summary_columns"]=$summary_columns;
                $report_customization_details["display_summary_columns"]=$display_summary_columns;
                $report_customization_details["decimal_places"]=$decimal_places;
                $report_customization_details["format_details"]=$format_details;
                $report_customization_details["format_date"]=$format_date;
              return $report_customization_details;
                }
        }

/*
Function        : assignPreferredColumns

Arguments        : &$arrays (reference),$preferred_columns

Action                : assigns the display names for column_names as preferred by the member

Author                : S.Gnanavel

Created on        : 11/11/2003
*/
function assignPreferredColumns(&$arrays,$preferred_columns,$decimal_places="",$format_details="",$default_order="",$format_date="")
        {
        if(!$arrays)
                return;
        foreach($arrays as $index=>$value_array)
                {
                if($preferred_columns)
                        {
                        foreach($preferred_columns as $variable_name=>$preferred_name)
                                {
                                if(!is_null($arrays[$index][$variable_name]))
                                        {
                                        $new_arrays[$index][$preferred_name]=trim($arrays[$index][$variable_name]);
                                        if($format_date[$variable_name] && $new_arrays[$index][$preferred_name])
                                                {
                                                $new_arrays[$index][$preferred_name]=showDate($new_arrays[$index][$preferred_name],$format_date[$variable_name]);
                                                }
                                        if(isset($decimal_places[$variable_name]) && $new_arrays[$index][$preferred_name]!="")
                                                {
                                                $new_arrays[$index][$preferred_name]=number_format($new_arrays[$index][$preferred_name],$decimal_places[$variable_name]);
                                                }
                                        if($format_details[$variable_name])
                                                {
                                                $eq_value_array=explode(",",$format_details[$variable_name]);
                                                foreach($eq_value_array as $equivalent_value)
                                                        {
                                                        list($display_value, $replace_value)=explode("=",$equivalent_value);
                                                        $new_arrays[$index][$preferred_name]=(trim($display_value)==trim($new_arrays[$index][$preferred_name]))?$replace_value:$new_arrays[$index][$preferred_name];
                                                        }
                                                }
                                        }
                                }
                        }
                }
        if($default_order=="DEFAULT_ORDER" && $new_arrays)
                {
                $key_order=array_keys($arrays[0]);
                foreach($new_arrays as $index=>$value_array)
                        {
                        foreach($key_order as $value)
                                {
                                $final_array[$index][$preferred_columns[$value]]=$new_arrays[$index][$preferred_columns[$value]];
                                }
                        }
                $new_arrays=$final_array;
                }
        $arrays=$new_arrays;
        }
        
function assignPreferredSummary(&$total_arrays,$preferred_columns)
        {
        $c=count($total_arrays);
        if($preferred_columns)
                {
                for($i=0;$i<$c;$i++)
                        {
                        foreach($preferred_columns as $column)
                                {
                                $final_total[$i][$column]=$total_arrays[$i][$column];
                                }
                        }
                }
        $total_arrays=$final_total;
        }

function generateGroupQueryString($group,$sort)
        {
        $query_string=array("sort_name[0]"=>key($sort),"sort_order[0]"=>current($sort));
        if($group)
                {
                $i=0;
                foreach($group as $group_name_key=>$group_order_value)
                        {
                        $query_string=array_merge($query_string,array("group_name[$i]"=>$group_name_key,"group_order[$i]"=>$group_order_value));
                        $i++;
                        }
                }
        return $query_string;
        }
        
/*
Function        : getColumnNames

Arguments        : $column_array
                                Format:
                                        array("odi.order_id||'-'||odi.item_id"        =>        "order_no", "odi.internal_order_no" =>        "internal_order_no")

Action                : returns a string suitable for fetching columns from database.
                                Format:
                                        order_id|'-'|item_id as \"order_no\", odi.internal_order_no as \"internal_order_no\"

Author                : S.Gnanavel

Created on        : 11/11/2003
*/
function getColumnNames($column_array)
        {
        foreach($column_array as $column_name=>$alias_name)
                $fetch_column.="$column_name as \"$alias_name\" , ";

        // removes trailing comma from $fetch_column
        $comma_index=strrpos($fetch_column,",");
        $fetch_column=substr($fetch_column,0,$comma_index-1);

        return $fetch_column;
        }

function formatConstraintArray(&$constraint_array)
        {
        $i=0;
        foreach($constraint_array as $name => $value)
                {
                $new_constraint_array[$i]["value"]=$value;
                $new_constraint_array[$i]["name"]=$name;
                 $i++;
                }
        $constraint_array=$new_constraint_array;
        }

function getUomConversions($from_uom,$to_uom="")
        {
        switch($from_uom)
                {
                case "sqft":
                 $conversion_value["sqft"]=1;
                 $conversion_value["sqmt"]=1/10.7639104;
                 $conversion_value["sqdm"]=9.290304;
                 break;
                case "sqmt":
                 $conversion_value["sqft"]=10.7639104;
                 $conversion_value["sqmt"]=1;
                 $conversion_value["sqdm"]=100;
                 break;
                case "sqdm":
                 $conversion_value["sqft"]=1/9.290304;
                 $conversion_value["sqmt"]=1/100;
                 $conversion_value["sqdm"]=1;
                 break;
		case "kigm":
                 $conversion_value["tone"]=1/1000;
                 $conversion_value["gram"]=1000;
                 $conversion_value["kigm"]=1;
                 break;
		 case "gram":
                 $conversion_value["tone"]=1/1000000;
                 $conversion_value["gram"]=1;
                 $conversion_value["kigm"]=1/1000;
                 break;
		 case "tone":
                 $conversion_value["tone"]=1;
                 $conversion_value["gram"]=1000000;
                 $conversion_value["kigm"]=1000;
                 break;
		 default:
		 $conversion_value[$to_uom]=1;
		 $conversion_value[$from_uom]=1;
		 break;
                }
        if($to_uom)
                return $conversion_value[$to_uom];
        else
                return $conversion_value;
        }

function convertAmount($rupees,$currency_id="INR")
        {
        $number=number_format($rupees,2,'.','');
        $rupees=floor($number);
        $paise=number_format($number-$rupees,2,'.','')*100;
        $array[4]="Thousand";
        $array[5]="Thousand";
        $array[6]="Lakh";
        $array[7]="Lakhs";
        $array[8]="Crore";
        $array[9]="Crores";
        if($paise)
                {
                if($currency_id == "INR")
                        $paise_name="Paise";
                if($currency_id == "USD")
                        $paise_name="Cents";
                if(!$currency_id)
                        $paise_name="Units";
                $ps=" $paise_name ".amt($paise);
                }
        while($rupees>999)
                {
                $size=strlen($rupees);
                $tdigit=floor($rupees/pow(10,strlen($rupees)-(($size%2)+1)));
                $amount.=amt($tdigit)." ".$array[$size]." ";
                $rupees=ceil(substr($rupees,($size%2)+1));
                }
        $amount.=" ".amt($rupees);
        //$amount=(trim($amount))?"$currency_id $amount":"";
        $amount=(trim($amount))?"$amount":"";
	unset($ps);
        $and=($amount&&$ps)?"and":"";
        $amount="$amount $and $ps Only";
        return $amount;
        }

function amt($rupees)
        {
        $num=array("","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen");
        $tnum=array("","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety");
        while($rupees)
                {
                $rupees=ceil($rupees);
                $size=strlen($rupees);
                switch($size)
                        {
                        case 1:
                                $amount.=" ".$num[$rupees];
                                $rupees=0;
                                break;
                        case 2:
                                if($rupees<20)
                                        {
                                        $amount.=$num[$rupees];
                                        $rupees=0;
                                        }
                                else
                                        {
                                        $tens=floor($rupees/10);
                                        $amount.=$tnum[$tens];
                                        $rupees=substr($rupees,1);
                                        }
                                break;
                        case 3:
                                $hunds=floor($rupees/100);
                                $amount=$num[$hunds]." Hundred ";
                                $rupees=substr($rupees,1);
                                if($rupees!="00")
                                        $amount.=" and ";
                                break;
                        }
                }
        return $amount;
        }

/******************************************************************************
        Function Name    : convertDbArray2String
        No. of Arguments : 4 (2 optional)
                         : &$array - array of values passed by reference
                           $fields - array of fields to apply the conversion
                           $search_string  - string to be searched
                           $replace_string - string to be replaced
        Action                 : For each field in the given array searches for the 
                           given string and replaces with the another string.
                           By default it replaces { } [ ]  with spaces.
        Returns                 : nothing
        Created on          : 21.04.2004
        Created by         : R.Lakshmi Narayanan
******************************************************************************/        
function convertDbArray2String(&$array,$fields,$search_string="",$replace_string="")
        {
        foreach($fields as $field_name)
                {
                for($i=0;$i<count($array);$i++)
                        {
                        $array[$i][$field_name]=ereg_replace("[{|}]","",$array[$i][$field_name]);
                        }
                }
        }

function generateGroupArray($group_name, $group_order)
        {
        $group_array=array();
        if($group_name)
                {
                foreach($group_name as $index=>$group_value)
                        {
                        if($group_value)
                                {
                                $group_array[$group_value]=$group_order[$index];
                                }
                        }
                }
        return $group_array;
        }
                
/* 
PARAMETERS
$arrays is a 2 dimensional array with structure array[][name]=value  
$group is an associative array with structure array[column to be grouped]=ascending or descending
$sort is an associative array with structure array[column to be sorted]=ascending or descending                
WORKING
$array is usually the array returned by database query, $group is formed by conditions selected by the user for
grouping the db query results. It can have any number of values, but usually will have 3 grouping for most reports. 
$sort by is also selected by the user and is used for sorting the records in the innermost grouped records
RETURNS
The grouped sorted array is returned. The array will have as many additional dimensions as the count of $group that
levels of grouping

USAGE
In reports after getting the query results - sort the array with the first selected group and the 
sort order of that group. Then, split the results into pages if needed and pass to the function. 

If not grouping is selected then sort by the final sorting selected before paginating. 

/*
PARAMETERS
$grouped_array - grouped arrays obtained from the groupArrays function
$group is an associative array with structure array[column to be grouped]=ascending or descending
$summary - is either blank of "summary_report"
declare $report_customization as global
$summary_details is declared global and gets values from each call of this function and accessible outside after 
the function exits. 
$heading is used only internally
WORKING

*/


function
showGroupedReport($array,$group=array(),$sort,$summary="",$heading=array(),
$serial_no=false,$nototal=false)
        {
        global $report_customization,$summary_details,$report_details,$show_column;
                $sorted_final_grouped_arrays=array();
		$first_sorted_group_arrays=array();
        //the last level grouping
        if(count($group)<= 1)
                {
                //group the array with the grouping selected with records sorted by the sorting chosen for that group
                
                $final_array=sortArray($array,key($group),current($group),"yes");
                
                //$final_array is in the form array[group_name]=grouped_arrays, now we take each of these grouped and sort them by the sorting selected.
                foreach($final_array as $final_array_key=>$final_array_value)
                        {
//                        print_r($final_array_value);
                        //sorting is done based on sort column - key($sort) and sort order - current($sort)
                        if(count($sort)==1)
                                {
                                $grouped_array=$final_array1[$final_array_key]=sortArray($final_array_value,key($sort),current($sort));
                                }
                        else
                                {
                                $first_sort_grouped_arrays=sortArray($final_array_value,key($sort),current($sort),"yes");
                                next($sort);
                                /*sort each grouped list by the order no in descending order*/
                                
				$sorted_final_grouped_arrays=array();
foreach($first_sort_grouped_arrays as $first_sort_group_array)
                                        {
                                        $first_sorted_group_array=sortArray($first_sort_group_array,key($sort),current($sort));
                                        $sorted_final_grouped_arrays=array_merge($sorted_final_grouped_arrays,$first_sorted_group_array);
                                        }
                                $grouped_array=$final_array1[$final_array_key]=$sorted_final_grouped_arrays;
                                unset($sorted_final_grouped_arrays);
                                reset($sort);
                                }

                        $heading[0][key($group)]=$final_array_key;
                        
                        //getTotal is written for each script and returns totals of required columns set in the function 
                        if($nototal==false)
			$total_array=getTotal($grouped_array);

                        assignPreferredSummary($total_array,$report_customization["display_summary_columns"]);
                        //$heading is generated with the name of each group, only if any grouping is there we need to generate summary report and group heading
                        if(count($heading)!=0)
                                {
                                //for generating summary report
                                if($summary=="summary_report")
                                        {
                                        //total array may have more than one row depending on the uom or currency etc sorting applied in getTotal function
                                        //print_r($total_array);
                                        if($total_array)
                                                {
                                                foreach($total_array as $row=>$field)
                                                        {
                                                        //generate summary details as an array with the headings and row(s) summary details values are added to the already existing values when this function is called recursively
                                                        $summary_details[]=array_merge($heading[0],$total_array[$row]);
                                                        }
                                                }
                                        //return $final_array1;
                                        }
                                else
                                        {
                                        if($_SESSION["guser_preferences"]["split_group"]=="yes" && $heading[0])
                                                {
                                                foreach($grouped_array as $row=>$record)
                                                        {
                                                        foreach($heading[0] as $grp=>$val)
                                                                {
                                                                if(isset($show_column[$grp]))
                                                                        {
                                                                        $heading[0][$grp]=$grouped_array[$row][$show_column[$grp]];
                                                                        }
                                                                unset($grouped_array[$row][$grp]);
                                                                }
                                                        }  
                                                echo "<br>";
                                                //show the columns chosen by the user with the name entered by them. Also set the decimal places or change the values as defined by the user using values in report customization print the heading for each group with required cell formatting using values in report customization
                                                $temp_heading=$heading;
                                                assignPreferredColumns($temp_heading,$report_customization["display_columns"],$report_customization["decimal_places"],$report_customization["format_details"],"DEFAULT_ORDER",$report_customization["format_date"]);
                                                doHorizontalTable($temp_heading,"60%","",$report_customization["column_style"]);
                                                }
                                        else
                                                {
                                                foreach($grouped_array as $row=>$record)
                                                        {
                                                        if($row > 0 && $group)
                                                                {
								
                                                                foreach($heading[0] as $grp=>$val)
                                                                        {
                                                                        $grouped_array[$row][$grp]=" ";
                                                                        }
                                                                }
                                                        else
                                                                {
                                                                foreach($heading[0] as $grp=>$val)
                                                                        {
                                                                        if(isset($show_column[$grp]))
                                                                                {
                                                                                $grouped_array[$row][$grp]=$grouped_array[$row][$show_column[$grp]];
                                                                                }
                                                                        }
                                                                }
                                                        }        
                                                
                                                foreach($heading[0] as $gname=>$gorder)
                                                        $display_order[$gname]=$report_customization["display_columns"][$gname];
                                                $old_order=$report_customization["display_columns"];
                                                $new_order=array_merge($display_order,$old_order);
                                                $report_customization["display_columns"]=$new_order;
                                                }
                                        //unset($heading);
                                        }
                                }
                        if ($summary!="summary_report")
                                {
                                //totals are to be shown as part of the report table after an empty line in the table                
                                $original_count=count($grouped_array);
                                //here the array gets an empty row at the end
                                foreach($grouped_array[0] as $key=>$value)
                                        {
                                        //$grouped_array[$original_count][$key]=" ";
                                        }
                                //create a row with totals in the corresponding columns - 
                                if($total_array)
                                        {
                                        foreach($total_array as $key=>$value)
                                                {
                                                //the row count will increase based on the number of rows in total array
                                                $nor=count($grouped_array);
                                                
                                                //for each column in the report check whether total is available 
                                                foreach($grouped_array[0] as $key1=>$value1)
                                                        {
                                                        if(isset($total_array[$key][$key1]))
                                                                {
                                                                $grouped_array[$nor][$key1]=$total_array[$key][$key1];
                                                                $summary_total_cols[0][$key1]=$total_array[$key][$key1];
                                                                }
                                                        else
                                                                {
                                                                $grouped_array[$nor][$key1]=" ";
                                                                }        
                                                        }
                                                }
                                        }
                                        setNA($grouped_array);
                                        assignPreferredColumns($grouped_array,$report_customization["display_columns"],$report_customization["decimal_places"],$report_customization["format_details"],"",$report_customization["format_date"]);
                                        assignPreferredColumns($summary_total_cols,$report_customization["display_columns"],$report_customization["decimal_places"],$report_customization["format_details"],"",$report_customization["format_date"]);
                                       $col_head = array_keys($grouped_array[0]);
                                        if ($summary_total_cols)
					{
					if(key($summary_total_cols[0]) == $col_head[0])
                                                {
                                                $grouped_array[$original_count][$col_head[0]] = "<b>Total:</b> ".$grouped_array[$original_count][$col_head[0]];
                                                }
                                                else
                                                {
                                                $grouped_array[$original_count][$col_head[0]] = "<b>Total:</b> ";       
                                                }
					} 
                                if($_SESSION["guser_preferences"]["split_group"]!="yes")
                                        {
                                        if(isset($report_details))
                                                $report_details=appendArrays($report_details,$grouped_array);
                                        else
                                                $report_details=$grouped_array;
					$cnt9=count($report_details);
					foreach($report_details[0] as $key2=>$value2)
	                                        $report_details[$cnt9][$key2]="<div class=\"border_bottom\"> <br /> </div>";
                                        }
                                else
					doHorizontalTable($grouped_array,"100%","",$report_customization["column_style"],true,true,$serial_no);
                                }
                        }
                return $final_array1;
                }
        else
                {
                $group_name=key($group);
                //if there are more than one level of grouping, group the array with the first grouping in the group array 
                $f_array=sortArray($array,key($group),current($group),"yes");
                //remove the above group condition from the group array 
                array_shift($group);
                //get the grouped arrays for each group obtained above and pass to the same function. For each level of grouping an array with additional dimension is created 
                foreach($f_array as $key=>$value)
                        {
                        $heading[0][$group_name]=$key;
                        $f_array[$key]=showGroupedReport($value,$group,$sort,$summary,$heading,$serial_no);
                        }
                return $f_array;
                }
        }
//append array2(target) to array1(source) filling blank fields with empty cells        
function appendArrays($array1,$array2,$append_type="APPEND")
        {
        $source=($append_type=="APPEND")?$array1:$array2;
        $target=($append_type=="APPEND")?$array2:$array1;
        //for each row in the target array append one row to the end of the source array 
        $target_count=count($target);
        if($target_count > 0)
                {
                for($i=0; $i<$target_count; $i++)
                        {
                        $index=count($source)-1;
                        if($source[$index])
                                {
                                foreach($source[$index] as $src_key=>$src_value)
                                        {
                                        $source[$index+1][$src_key]=(isset($target[$i][$src_key]))?$target[$i][$src_key]:" ";
                                        }
                                }
                        }
                }
        elseif($target_count == 0)
                {
                $index=count($source)-1;
                if($source[$index])
                        {
                        foreach($source[$index] as $src_key=>$src_value)
                                {
                                $source[$index+1][$src_key]="&nbsp;";
                                }
                        }
                }
        return $source;
        }

function validateArrayValues($arrays)
        {
        global $form;
        foreach($arrays as $key=>$value)
                {
                $form->validate($value);
                if($form->errors)
                        {
                        $errors[$key] = $form->errors;
                        }
                }
        return flipArrayKeys($errors);        
        }
function validateArrayValuesNew($arrays)
        {
        global $dv;
        foreach($arrays as $key=>$value)
                {
                $dv->validate($value);
                if($dv->errors)
                        {
                        $errors[$key] = $dv->errors;
                        unset($dv->errors);
                        }
                }
        return $errors;
        }
function checkArrayNotEmpty($arrays)
        {
        foreach($arrays as $key=>$value)
                {
                if(is_array($value))
                        {
                        checkArrayNotEmpty($value);
                        }
                else
                        {
                        if(trim($value)!="")
                                return true;
                        }        
                }
        return false;
        }

function getFilledRows($array,$columns="")
        {
        $columns=($columns)?$columns:array_keys($array);
        $array=flipArrayKeys($array,$columns);
        foreach($array as $key=>$value)
                {
                if(checkArrayNotEmpty($value))
                        {
                        $new_array[$key]=$value;
                        }
                }
        return $new_array;
        }        

function flipArrayKeys($array,$columns="")
        {
        if($array)
                {
                foreach($array as $key=>$value)
                        {
                        if(is_array($value))
                                {
                                foreach($value as $key1=>$value1)
                                        {
                                        if($columns)
                                                {
                                                foreach($columns as $column_name)
                                                        {
                                                        if($column_name==$key)
                                                                $new_array[$key1][$key]=$value1;
                                                        }
                                                }
                                        else
                                                {
                                                $new_array[$key1][$key]=$value1;
                                                }
                                        }
                                }
                        }
                }
        return $new_array;
        }
/*****************************************************************************************
Function Name                 :mergeTableArrays
No. of Arguments        :3
Arguments                :$table_details1 -  Associative array of records to be displayed in
                                table format.
                         $table_details2 -  Associative array of records to be displayed in
                                table format.
			$merge_key - array of columns which are present in both the arrays and are to be merged into a single column	
Action                    : merges $table_details1 and $table_details2 to have all the values present in $merge_key in both the arrays
Returns                        : merged Array ready to be used in table forming functions
Created By                : Ma Sivakumar
Created On                :14 March 2005
Modified By                :Ma Sivakumar
Modified On                :14 March 2005
*****************************************************************************************/

function mergeTableArrays($table_details1,$table_details2,$merge_key)
        {
        //for each row in $table_details1 merge the row in second table where the $merge_key is identical, if the key is not present in the second table, leave it blank, do the same for the values in second table which are not present in first table
        $count1=count($table_details1);
        for ($i=0; $i<$count1; $i++)
		{
		$size_value=$table_details1[$i][$merge_key];
		$merged_array[$i][$merge_key]=$table_details1[$i][$merge_key];
		$array1_keys=array_keys($table_details1[$i]);
		$array1_unique_key=$array1_keys[1];
		$array2_keys=array_keys($table_details2[$i]);
		$array2_unique_key=$array2_keys[1];
		$merged_array[$i][$array1_unique_key]=$table_details1[$i][$array1_unique_key];
		$merged_array[$i][$array2_unique_key]=$table_details2[$i][$array2_unique_key];
		}
	return $merged_array;
	}

	
	        
/*function array_duplicate($main_array,$fields)
        {
        $bool=true;
        $count=count($main_array);
        for($i=0;$i<$count;$i++)
                {
                for($j=$i+1;$j<$count;$j++)
                        {
                        foreach($fields as $key=>$value)
                                {
                                $bool=($bool && $main_array[$i][$value]==$main_array[$j][$value]);
                                }
                        if($bool)
                                return $bool;
                        else
                                $bool=true;
                        }
                }
        return false;
        }*/
	
	/*
	
	
Function        : getReportDetailsOld

Arguments        : $member_id, $report_id

Action                : Fetches the column_names and display names for the given $report_id preferred by the member

Author                : S.Gnanavel

Created on        : 11/11/2003
*/
function getReportDetailsOld($member_id,$report_code)
        {
        include(DOCINCLUDES."global_files/tables.inc");
	include ("global_files/global_pgsql.inc");
	global $db;
	$sql= new pgSql();
	$db= new cDatabase();
        // get the columns for the report from member's table
        $db->query="select mcm.fetch_column, mp.privilege_desc, mcm.permission, mcm.db_column_name, mcm.script_variable_name, rc.display_name, rc.display_order, rc.style, rc.display_summary, rc.decimal_places, rc.format_details, rc.format_date from $master_column_mapping_table mcm, $report_customization_table rc, $master_privilege_table mp, $master_report_table mr
                                where mr.report_code='$report_code' and mcm.column_id=rc.column_id and rc.display_order is not NULL and mcm.privilege_id=mp.privilege_id and mr.report_id=mcm.report_id order by rc.display_order;";
        $db->runQuery();
        $report_details=$db->returnArrays();

        // if the member has not set the preferences then fetch the details from master table
        if(!$report_details)
                {
                $db->query="select mcm.fetch_column, mp.privilege_desc, mcm.permission, mcm.db_column_name, mcm.script_variable_name, mrc.display_name, mrc.display_order, mrc.style, mrc.display_summary, mrc.decimal_places, mrc.format_details, mrc.format_date  from $master_column_mapping_table mcm, $master_report_customization_table mrc, $master_privilege_table mp, $master_report_table mr
                                where mr.report_code='$report_code' and mcm.column_id=mrc.column_id and mrc.display_order is not NULL  and mcm.privilege_id=mp.privilege_id and mr.report_id=mcm.report_id order by mrc.display_order;";
                $db->runQuery();
                $report_details=$db->returnArrays();
                }
	  if($report_details)
                {
                for($i=0;$i<count($report_details);$i++)
                        {
                        //if(strchr($_SESSION["gprivilege"][$member_id][$report_details[$i]["privilege_desc"]],$report_details[$i]["permission"]))
                                //{
                                $script_variable_name=$report_details[$i]["script_variable_name"];
                                if($report_details[$i]["fetch_column"]=='t')
                                        {
                                        $db_column_name=$report_details[$i]["db_column_name"];
                                        $column_mapping[$db_column_name]=$script_variable_name;
                                        }
                                if($report_details[$i]["display_summary"])
                                        {
                                        $summary_columns[]=$script_variable_name;
                                        }
                                // get the preferred name against script variable name only when display_order is specified
                                if($report_details[$i]["display_order"] > 0)
                                        {
                                        $display_name=$report_details[$i]["display_name"];
                                        $display_columns[$script_variable_name]=$display_name;
                                        if($report_details[$i]["style"])
                                                $column_style[$display_name]=$report_details[$i]["style"];
                                        if($report_details[$i]["display_summary"] == 't')
                                                $display_summary_columns[]=$script_variable_name;
                                        if($report_details[$i]["decimal_places"] != "")
                                                $decimal_places[$script_variable_name]=$report_details[$i]["decimal_places"];
                                        if($report_details[$i]["format_details"])
                                                $format_details[$script_variable_name]=$report_details[$i]["format_details"];
                                        if($report_details[$i]["format_date"])
                                                $format_date[$script_variable_name]=$report_details[$i]["format_date"];
                                        }
                                //}
                        }
               	// return the details of the columns to be fetched from database and display names for the report
                $report_customization_details["column_mapping"]=$column_mapping;
                $report_customization_details["display_columns"]=$display_columns;
                $report_customization_details["column_style"]=$column_style;
                $report_customization_details["summary_columns"]=$summary_columns;
                $report_customization_details["display_summary_columns"]=$display_summary_columns;
                $report_customization_details["decimal_places"]=$decimal_places;
                $report_customization_details["format_details"]=$format_details;
                $report_customization_details["format_date"]=$format_date;
              return $report_customization_details;
                }
        }

//  [created : 01/09/2007, 10:58:13 AM]
// by G.M.Sundar
//  Description:
//  ============
//  The function used to show report in tabs
// $div_details=associative arrays--details below
// 	div_details[divname][table style (h or v)][Title]
// $width =width of the tabs
// $title=Title for the tabs


 

function doTabReport($div_details,$width="100%",$title="")
{


echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" height=150 width=140>";
	echo "<tr align=\"center\">";
		echo "<td align=\"center\">";
			echo "<font size=3>".$title ."</font><BR>";
		echo "</td>";
	echo "</tr>";
	echo "<tr>";
		echo "	<td valign=top height=29>";
    			echo "<script type=\"text/javascript\" language=\"JavaScript1.2\" src=\"../jscripts/tabs-work2.js\"></script>";

  		echo "</td>";
	echo "</tr>";
	echo "<tr>";
  		echo "<td height=500>";
		    echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" height=500 bgcolor=#E4F3FB>";
    			echo "<tr>";
      				echo "<td valign=top>&nbsp;<br>";
foreach($div_details as $key=>$value)
{
	echo "<div id=".$key." style=\"height: 0%; visibility: hidden;\" class=\"tabPage\">";
		foreach($value as $key1=>$value1)
		{
			if($key1=='v')
			{
			
			foreach($value1 as $key2=>$value2)
				foreach($value2 as $key3=>$value3)
					if($value3)
					doVerticalTable($value3,"",$key3);
					else
					 echo "No Records";
			}
			else
			{
			foreach($value1 as $key2=>$value2)
				foreach($value2 as $key3=>$value3)
					if($value3)
					doHorizontalTable($value3,"",$key3);
					else
					echo "<blink>No Records<blink>";
			
			}
		}
	echo "</div>";

}

	
    				echo "</td>";
    			echo "</tr>";
    		echo "</table>";

//   	echo "</td>";
// echo "</tr>";
//  echo "</td>";
// echo "</tr>";
// echo "</table>";



}
function assignDisplayName($customization_id)
        {
        include(DOCINCLUDES."global_files/global_pgsql.inc");
	$db= new cDatabase();
         $db->query="SELECT db_column_name,display_name from _100244._100244report_customization rc join _100244.master_column_mapping mcp on mcp.column_id=rc.column_id where customization_id=$customization_id;";
	$db->runQuery();
	$column_names_array=$db->returnArrays();
	$column_names="";
	$count_val=1;
	foreach($column_names_array as $key=>$value)
	{


		if($count_val=='1')
		{
			$column_names=$value['db_column_name'].' as "'. $value['display_name'].' "';
			$count_val++;
		}
		else
		{
		$column_names.=', '.$value['db_column_name'].' as "'. $value['display_name'].' " ';
			
			$count_val++;
		}	
	}
return $column_names;
	}	
?>
